/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ui;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import model.CourseGrade;
import model.Person;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import constant.ColumnEnum;
import constant.CourseTypeEnum;
import java.awt.Font;
import javax.swing.UIManager;
import javax.swing.plaf.FontUIResource;
import javax.swing.table.TableRowSorter;
import model.Grades;
import util.GradeExcelReader;

/**
 *
 * @author 乐山
 */
public class MainFrame extends javax.swing.JFrame {

    private Workbook wb;
    private Map<String, Person> personsMap;
    private List<Person> personList;

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        gradeFileChooser = new javax.swing.JFileChooser();
        keywordTextField = new javax.swing.JTextField();
        searchButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        resultTable = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        stuInfoTable = new javax.swing.JTable();
        loadButton = new javax.swing.JButton();
        searchButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("学生课程信息搜索");
        setResizable(false);

        keywordTextField.setFont(new java.awt.Font("宋体", 1, 14)); // NOI18N
        keywordTextField.setPreferredSize(new java.awt.Dimension(76, 26));

        searchButton.setFont(new java.awt.Font("宋体", 1, 14)); // NOI18N
        searchButton.setText("搜索");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "搜索结果", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("宋体", 1, 14))); // NOI18N

        resultTable.setFont(new java.awt.Font("宋体", 1, 14)); // NOI18N
        resultTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "班级", "学号", "姓名"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        resultTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                resultTableMouseClicked(evt);
            }
        });
        resultTable.setRowSorter(new TableRowSorter<TableModel>(resultTable.getModel()));
        jScrollPane1.setViewportView(resultTable);
        resultTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "学生修习统计信息", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("宋体", 1, 14))); // NOI18N

        stuInfoTable.setFont(new java.awt.Font("宋体", 1, 14)); // NOI18N
        stuInfoTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "修习类别", "已通过学分", "所需学分总数", "是否达成"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(stuInfoTable);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE)
        );

        loadButton.setFont(new java.awt.Font("宋体", 1, 14)); // NOI18N
        loadButton.setText("加载数据库");
        loadButton.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        loadButton.setPreferredSize(new java.awt.Dimension(75, 25));
        loadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadButtonActionPerformed(evt);
            }
        });

        searchButton1.setFont(new java.awt.Font("宋体", 1, 14)); // NOI18N
        searchButton1.setText("查看");
        searchButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(loadButton, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(keywordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(searchButton, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(searchButton1))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(keywordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(loadButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(searchButton)
                        .addComponent(searchButton1)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {keywordTextField, loadButton, searchButton, searchButton1});

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents
    private boolean loadToCourseGradeListAndMap(Workbook wb) {
        if (wb == null) {
            return false;
        }
        personsMap = new HashMap<>();
        HashSet<Person> personSet = new HashSet<Person>();
        Sheet sheet0 = wb.getSheetAt(0);
        Row row = null;
        for (int i = 1; i < sheet0.getLastRowNum(); i++) {
            row = sheet0.getRow(i);
            //读取学生
            Cell idCell = row.getCell(ColumnEnum.ID.getColumn());
            Cell nameCell = row.getCell(ColumnEnum.NAME.getColumn());
            Cell clazzCell = row.getCell(ColumnEnum.CLAZZ.getColumn());
            String id = idCell.getStringCellValue();
            String name = nameCell.getStringCellValue();
            String clazz = clazzCell.getStringCellValue();
            //读取成绩
            Cell courseNameCell = row.getCell(ColumnEnum.COURSENAME.getColumn());
            Cell typeCell = row.getCell(ColumnEnum.TYPE.getColumn());//修习类别
            Cell creditCell = row.getCell(ColumnEnum.CREDIT.getColumn());//学分
            Cell examStatCell = row.getCell(ColumnEnum.EXAMSTAT.getColumn());//考试性质
            Cell finaCell = row.getCell(ColumnEnum.FINALGRADE.getColumn());
            String cName = courseNameCell.getStringCellValue();
            String type = typeCell.getStringCellValue();
            Double credit = Double.valueOf(creditCell.getStringCellValue());
            String examStat = examStatCell.getStringCellValue();
            Integer finalGrade = Integer.valueOf(finaCell.getStringCellValue());
            
            
            CourseGrade courseGrade = new CourseGrade(cName, type, examStat, credit, finalGrade);
            
            if (!personsMap.containsKey(id)) {
                Person person = new Person(id, name, clazz);
                personsMap.put(id, person);
                personSet.add(person);
                person.putGrade(courseGrade);
            } else {
                Person person = personsMap.get(id);
                personSet.add(person);
                person.putGrade(courseGrade);
            }
            personList = new ArrayList<Person>(personSet);
        }
        return true;
    }
    private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadButtonActionPerformed
        FileNameExtensionFilter filter = new FileNameExtensionFilter("XLS&XLSX",
                "XLS", "XLSX");
        gradeFileChooser.setFileFilter(filter);
        int val = gradeFileChooser.showOpenDialog(this);
        if (val == JFileChooser.APPROVE_OPTION) {
            File file = gradeFileChooser.getSelectedFile();
            //System.out.println("fileName=" + file.getAbsolutePath());
            wb = GradeExcelReader.readWorkbookFromExcelFile(file.getAbsolutePath());
            if (loadToCourseGradeListAndMap(wb))
                JOptionPane.showMessageDialog(this, "载入完毕!");
            else
                JOptionPane.showMessageDialog(this, "载入失败!");
        }
        

    }//GEN-LAST:event_loadButtonActionPerformed

    private List<Person> searchPersonsByKeyword(String keyword, List<Person> persons) {
        List<Person> resultList = new ArrayList<>();
        for (Person e : persons) {
            if (e.getName().contains(keyword ) || e.getId().contains(keyword))
                resultList.add(e);
        }
        return resultList;
    }
    
    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
        if (personsMap == null || personList == null){
            JOptionPane.showMessageDialog(this, "还未载入数据库!");
            return;
        }
        DefaultTableModel model = (DefaultTableModel)resultTable.getModel();
        model.setRowCount(0);//清空当前表格
        String keyword = keywordTextField.getText().trim();
        if (keyword.isBlank()){
            JOptionPane.showMessageDialog(this, "未输入任何关键字!");
            return;
        }
        List<Person> resultPersons =  searchPersonsByKeyword(keyword, personList);
        if (resultPersons.size() == 0){
            JOptionPane.showMessageDialog(this, "未找到任何符合条件的记录！");
            return;
        }
        for (Person e : resultPersons) {
            Object[] o = {e.getClazz(), e.getId(),e.getName()};
            model.addRow(o);
        }
        
    }//GEN-LAST:event_searchButtonActionPerformed
    
    /**
     * 为JTable准备数据。Object[]
     * @param grade
     * @param cte
     * @return 
     */
    private Object[] generateStudyStatInfo(Grades grade, CourseTypeEnum cte) {
        Object[] result = new Object[4];
        result[0] = cte.getName();//修习类别
        result[2] = cte.getCredit();
        switch (cte) {
            case BASICEC:
                result[1] = grade.calcBasicECCredit(); 
                result[3] = grade.isPassed(CourseTypeEnum.BASICEC)?"通过":"未通过";
                break;
            case SPECIALEC:
                result[1] = grade.calcSpecialECCredit();
                result[3] = grade.isPassed(CourseTypeEnum.SPECIALEC)?"通过":"未通过";;
                break;
            case SPECIALRC:
                result[1] = grade.calcSpeicalRCCredit();
                result[3] = grade.isPassed(CourseTypeEnum.SPECIALRC)?"通过":"未通过";;
                break;    
            default:
                return null;
        }
       /* Double r1 = (Double)result[1];
        Double r2 = (Double)result[2];
        if (Double.compare(r1, r2)>=0){
            result[3] = "已通过";
        }else{
            result[3] = "未通过";
        }*/
        return result;
    }
    
    private void resultTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resultTableMouseClicked
        int selectedRow = resultTable.getSelectedRow();
        TableModel model = resultTable.getModel();
        if (selectedRow != -1){
            String id = (String)model.getValueAt(selectedRow, 1);
            Person p = personsMap.get(id);
            //修习类别、已通过学分，所需总学分数，是否达成
            Object[] result1 = generateStudyStatInfo(p.getGrade(), CourseTypeEnum.BASICEC);
            Object[] result2 = generateStudyStatInfo(p.getGrade(), CourseTypeEnum.SPECIALEC);
            Object[] result3 = generateStudyStatInfo(p.getGrade(), CourseTypeEnum.SPECIALRC);
            DefaultTableModel dtm = (DefaultTableModel)stuInfoTable.getModel();
            dtm.setRowCount(0);
            dtm.addRow(result1);
            dtm.addRow(result2);
            dtm.addRow(result3);
        }
        
    }//GEN-LAST:event_resultTableMouseClicked

    private void searchButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButton1ActionPerformed
        int selectedRow = resultTable.getSelectedRow();
        TableModel model = resultTable.getModel();
        if (selectedRow != -1){
            String id = (String)model.getValueAt(selectedRow, 1);
            Person p = personsMap.get(id);
            StuCoursesInfoDialog scInfoDialog = new StuCoursesInfoDialog(this, true, p);
            scInfoDialog.setVisible(true);
            
        }
    }//GEN-LAST:event_searchButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
                //UIManager.put("OptionPane.messageFont", new FontUIResource(new Font("Monospace", Font.PLAIN, 13)));
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFileChooser gradeFileChooser;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField keywordTextField;
    private javax.swing.JButton loadButton;
    private javax.swing.JTable resultTable;
    private javax.swing.JButton searchButton;
    private javax.swing.JButton searchButton1;
    private javax.swing.JTable stuInfoTable;
    // End of variables declaration//GEN-END:variables

    

    
}
